package com.lee.common.base

import android.content.pm.ActivityInfo
import android.os.Bundle
import android.os.Handler
import android.os.Looper
import android.os.PersistableBundle
import android.view.View
import android.view.ViewGroup
import android.widget.FrameLayout
import android.widget.RelativeLayout
import android.widget.TextView
import androidx.appcompat.app.AppCompatActivity
import androidx.core.content.ContextCompat
import androidx.databinding.DataBindingUtil
import androidx.databinding.ViewDataBinding
import androidx.lifecycle.MutableLiveData
import cn.jiguang.analytics.android.api.JAnalyticsInterface
import com.alibaba.android.arouter.launcher.ARouter
import com.lee.common.R
import com.lee.common.databinding.BaseActivityLayoutBinding
import com.lee.common.observer.LoadingObserver
import com.lee.common.utils.MyActivityManager
import com.lee.common.widget.EmptyView
import com.xuexiang.xui.utils.StatusBarUtils
import org.greenrobot.eventbus.EventBus

abstract class BaseActivity<T : ViewDataBinding> : AppCompatActivity() {

    val mContext by lazy { this }

    lateinit var bindingView: T
    private var titleString = ""

    private lateinit var baseBinding: BaseActivityLayoutBinding
    val loadingState = MutableLiveData<Boolean>()

    override fun onCreate(savedInstanceState: Bundle?, persistentState: PersistableBundle?) {
        MyActivityManager.instance.addActivity(this)
        ARouter.getInstance().inject(this)
        requestedOrientation = ActivityInfo.SCREEN_ORIENTATION_PORTRAIT
        setLight(true)
        super.onCreate(savedInstanceState, persistentState)
    }

    val emptyView by lazy {
        EmptyView(this)
    }

    override fun onResume() {
        super.onResume()
        JAnalyticsInterface.onPageStart(applicationContext, this.javaClass.canonicalName)
    }

    override fun onPause() {
        super.onPause()
        //统计
        JAnalyticsInterface.onPageEnd(applicationContext, this.javaClass.canonicalName)
    }

    /**
     * 数据返回空显示的View
     */
    fun getEmptyView(): View {
        return emptyView.getEmptyView()
    }

    /**
     * 正在获取数据时显示View
     */
    fun getLoadingView(): View {
        return emptyView.getLoadingView()
    }

    /**
     * 获取数据错误时显示View
     */
    fun getErrView(): View {
        return emptyView.getErrView()
    }


    companion object {

        /**
         * 获取一个 Handler 对象
         */
        val handler = Handler(Looper.getMainLooper())
    }

    override fun setContentView(layoutResID: Int) {

        baseBinding =
            DataBindingUtil.inflate(layoutInflater, R.layout.base_activity_layout, null, false)
        bindingView = DataBindingUtil.inflate(layoutInflater, layoutResID, null, false);
        bindingView.lifecycleOwner = this

        val parameter = RelativeLayout.LayoutParams(
            ViewGroup.LayoutParams.MATCH_PARENT,
            ViewGroup.LayoutParams.MATCH_PARENT
        )
        bindingView.root.layoutParams = parameter
        baseBinding.container.addView(bindingView.root)

        initVew()
        setData()
        if (titleString != "")
            setTitle(titleString)
        setBackClick()
        loadingState.observe(this, LoadingObserver(this))
        super.setContentView(baseBinding.root)
    }


    protected fun getColor21(color: Int): Int {
        return ContextCompat.getColor(this, color)
    }

    protected fun setBackClick() {
        baseBinding.back.setOnClickListener {
            finish()
        }
    }


    override fun onDestroy() {
        super.onDestroy()
        bindingView?.unbind()
        MyActivityManager.instance.removeActivity(this)
    }

    open fun setLeftVisible(isVisible: Boolean) {
        if (::baseBinding.isInitialized) {
            baseBinding.back.visibility = if (isVisible) View.VISIBLE else View.GONE
        }
    }

    open fun setTitleBarGone() {
        val params = FrameLayout.LayoutParams(
            ViewGroup.LayoutParams.MATCH_PARENT,
            ViewGroup.LayoutParams.MATCH_PARENT
        )
        params.topMargin = 0
        baseBinding.container.layoutParams = params

        baseBinding.titleBar.visibility = View.GONE
    }

    /**
     * 关闭当前activity
     */
    protected open fun finishActivity() {
        finish()
    }

    /**
     * 设置标题
     */
    override fun setTitle(resId: Int) {
        setTitle(getString(resId))
    }

    /**
     * 设置标题
     */
    open fun setTitle(value: String) {
        titleString = value
        if (::baseBinding.isInitialized) {
            baseBinding.title.text = titleString
        }
    }


    /**
     * 设置标题栏背景色
     */
    open fun setBarBgColor(color: Int) {
        baseBinding.titleBar.setBackgroundColor(color)
    }


    /**
     * 设置右边文本
     */
    open fun setRightText(value: String?): TextView? {
        if (::baseBinding.isInitialized) {
            baseBinding.rightTitle.text = value
            baseBinding.rightTitle.visibility = View.VISIBLE
            return baseBinding.rightTitle
        }
        return null
    }

    protected open fun onRightLayoutListener() {

    }

    /**
     * 设置右边图片
     */
    open fun setRightImage(resourceId: Int) {
    }

    /**
     * 设置左边文本
     */
    open fun setLeftText(value: String?) {
    }


    /**
     * 设置左边图片
     */
    open fun setLeftImage(resId: Int) {

    }

    /***
     *
     * 初始化视图
     */
    abstract fun initVew()

    /***
     * 获取数据
     */
    abstract fun setData()

    open fun registerEvent(objects: Any) {
        EventBus.getDefault().apply {
            if (!isRegistered(objects)) {
                register(objects)
            }
        }
    }

    fun destroyEvent(activity: Any) {
        EventBus.getDefault().unregister(activity)
    }

    protected open fun setLight(light: Boolean) {
        if (light) {
            StatusBarUtils.setStatusBarLightMode(this)
        } else {
            StatusBarUtils.setStatusBarDarkMode(this)
        }
    }

}